package org.lanyu.springainovel.common.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.lanyu.springainovel.common.entity.User;
import org.lanyu.springainovel.common.mapper.UserMapper;
import org.lanyu.springainovel.common.service.UserCacheService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

/**
 * 用户缓存服务实现类
 * 使用Spring Cache抽象层实现用户信息缓存
 */
@Service
@Slf4j
public class UserCacheServiceImpl implements UserCacheService {
    
    @Autowired
    private UserMapper userMapper;
    
    @Override
    @Cacheable(value = "users", key = "#username")
    public User getUserByUsername(String username) {
        log.debug("从数据库查询用户: {}", username);
        
        User user = userMapper.selectOne(
            new com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper<User>()
                .eq(User::getUsername, username)
        );
        
        if (user != null) {
            // 确保密码不为null，如果为null则重新查询
            if (user.getPassword() == null) {
                user = userMapper.selectById(user.getId());
            }
        } else {
            System.out.println("未找到用户: " + username);
        }

        return user;
    }
    
    @Override
    @Cacheable(value = "users", key = "#userId")
    public User getUserById(Long userId) {
        log.debug("从数据库查询用户ID: {}", userId);
        return userMapper.selectById(userId);
    }
    
    @Override
    public void cacheUser(User user) {
        log.debug("缓存用户信息: {}", user.getUsername());
        // 使用@CachePut注解需要返回值，所以这里手动调用缓存更新
        updateUserInCache(user);
    }
    
    @Override
    public void updateUser(User user) {
        log.debug("更新缓存中的用户信息: {}", user.getUsername());
        // 使用@CachePut注解需要返回值，所以这里手动调用缓存更新
        updateUserInCache(user);
    }
    
    /**
     * 内部方法，用于更新缓存
     * @param user 用户信息
     * @return 更新后的用户信息
     */
    @CachePut(value = "users", key = "#user.username")
    private User updateUserInCache(User user) {
        return user;
    }
    
    @Override
    @CacheEvict(value = "users", key = "#userId")
    public void evictUser(Long userId) {
        log.debug("从缓存中删除用户ID: {}", userId);
    }
    
    @Override
    @CacheEvict(value = "users", key = "#username")
    public void evictUser(String username) {
        log.debug("从缓存中删除用户: {}", username);
    }
    
    @Override
    @CacheEvict(value = "users", allEntries = true)
    public void clearAll() {
        log.debug("清空所有用户缓存");
    }
}